package com.bbx.taxi.client.Activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Bind;
import rx.functions.Action1;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.login.LoginActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.ContactPersonMsg;
import com.bbx.taxi.client.DB.ContactsDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.bbx.taxi.client.Util.Phone;
import com.bbx.taxi.client.Util.StringFilter;
import com.bbx.taxi.client.widget.MaxByteLengthEditText;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.pullListView.PullToRefreshLayout.OnRefreshListener;
import com.example.mylistview.pullListView.PullableListView;
import com.example.mylistview.pullListView.PullableListView.OnLoadListener;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.MyListView.OnMenuItemClickListener;
import com.example.mylistview.swipemenu.MyListView.OnSwipeListener;
import com.example.mylistview.swipemenu.SwipeMenu;
import com.example.mylistview.swipemenu.SwipeMenuCreator;
import com.example.mylistview.swipemenu.SwipeMenuItem;
import com.tbruyelle.rxpermissions.RxPermissions;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 联系人
 */
public class ContactPersonActivity extends BaseBBXActivity implements
		OnItemClickListener, OnFocusChangeListener ,OnLoadListener,OnRefreshListener{
	@Bind(R.id.layout_addresslist)
	LinearLayout layout_addresslist;
	@Bind(R.id.telephone)
	EditText telephone;
	@Bind(R.id.contactperson)
	MaxByteLengthEditText contactperson;
	@Bind(R.id.iv_contact_del)
	ImageView iv_contact_del;
	@Bind(R.id.iv_tel_del)
	ImageView iv_tel_del;
	@Bind(R.id.MyListView)
	MyListView mMyListView;
	@Bind(R.id.layout_prompt)
	RelativeLayout layout_prompt;
	Button btn_clear;
	View clearView;
	private String username, usernumber;
	private List<Map<String, String>> list = new ArrayList<Map<String, String>>();
	private CommonContactAdapter mCommonContactAdapter;
	private Handler handler;
	/** 常用联系人数据库 */
	private ContactsDB db_contacts;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.contactperson);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initView() {
		setTitle(true, getString(R.string.title_contacts), -1, getString(R.string.title_right_confirm));
		handler = new Handler();
		mCommonContactAdapter = new CommonContactAdapter(this, list);
		clearView = LayoutInflater.from(this).inflate(R.layout.item_foot_clear,
				null);
		btn_clear = (Button) clearView.findViewById(R.id.btn_clear);
		mMyListView.setAdapter(mCommonContactAdapter);
		mMyListView.setOnItemClickListener(this);
		mMyListView.hideLoad();
		layout_addresslist.setOnClickListener(this);
		btn_clear.setOnClickListener(this);
		db_contacts = new ContactsDB();
		iv_contact_del.setOnClickListener(this);
		iv_tel_del.setOnClickListener(this);
		readAllDB();
		initswipe();
		 if (mCommonContactAdapter.getCount() == 0) {
		 mMyListView.removeFooterView(clearView);
		 
		 } else {
		 mMyListView.addFooterView(clearView,null,false);
		 layout_prompt.setVisibility(View.VISIBLE);
		 }
		 /////////////////////////////
			Intent intent = getIntent();
			if (intent.getExtras() != null) {
				username = intent.getExtras().getString(
						ContactPersonMsg.extra_contact_name);
				usernumber = intent.getExtras().getString(
						ContactPersonMsg.extra_contact_phone);
			}
			telephone.setOnFocusChangeListener(this);
			contactperson.setOnFocusChangeListener(this);
			contactperson.setText(username);
			contactperson.setSelection(contactperson.getText().length());
			telephone.setText(usernumber);
			telephone.setSelection(telephone.getText().length());
			contactperson.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2,
						int arg3) {
				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
				}

				@Override
				public void afterTextChanged(Editable s) {
					if (!s.toString().isEmpty()) {
						iv_contact_del.setVisibility(View.VISIBLE);
					} else {
						iv_contact_del.setVisibility(View.GONE);
					}
				}
			});
			telephone.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2,
						int arg3) {
				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
				}

				@Override
				public void afterTextChanged(Editable s) {
					if (!s.toString().isEmpty()) {
						iv_tel_del.setVisibility(View.VISIBLE);
					} else {
						iv_tel_del.setVisibility(View.GONE);
					}
				}
			});
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	/**
	 * 读取所有数据
	 */
	public void readAllDB() {
		list.clear();
		Cursor c = db_contacts.onQuery(Value.CONTACTS_TYPE_COLLECTE);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				list.add(map);
			} while (c.moveToNext());
		}
		c = db_contacts.onQuery(Value.CONTACTS_TYPE_HISTORY);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				list.add(map);
			} while (c.moveToNext());
		}
		mCommonContactAdapter.notifyDataSetChanged();
		c.close();
		db_contacts.onColse();
	}

	/**
	 * 写入数据库
	 */
	public void onWriteDB(String name, String tel, String collection) {
		db_contacts.onWrite(name, tel, collection);
	}

	/**
	 * 更新数据(顺序)
	 */
	public void onUpdate_sequence(String id, String name, String tel,
			String collection) {
		db_contacts.onUpdate_sequence(id, name, tel, collection);
	}

	/**
	 * 更新数据
	 */
	public void onUpdate(String id, String name, String tel, String collection) {
		db_contacts.onUpdate(id, name, tel, collection);
	}

	/**
	 * 根据收藏或历史进行删除
	 */
	public void onDelete(String isCollection) {
		db_contacts.onDeleteType(isCollection);
		readAllDB();
	}

	/**
	 * 删除一个数据
	 */
	public void onDelete(String rowId, int position) {
		db_contacts.onDelete(rowId);
		list.remove(position);
		mCommonContactAdapter.notifyDataSetChanged();
		if (mCommonContactAdapter.getCount() == 0) {
			mMyListView.removeFooterView(clearView);
			
		} else {
			mMyListView.addFooterView(clearView, null, false);
			layout_prompt.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 初始化ListView的Item菜单
	 */
	public void initswipe() {

		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				openItem.setBackgroundColor(getResources()
						.getColor(R.color.red));
				// set item width
				openItem.setWidth(dp2px(65));
				// set item title
				openItem.setTitle(getString(R.string.delete));
				// set item title fontsize
				openItem.setTitleSize(18);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
				menu.addMenuItem(openItem);

				// // create "delete" item
				// SwipeMenuItem deleteItem = new SwipeMenuItem(
				// getApplicationContext());
				// // set item background
				// deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
				// 0x3F, 0x25)));
				// // set item width
				// deleteItem.setWidth(dp2px(90));
				// // set a icon
				// deleteItem.setIcon(R.drawable.ic_delete);
				// // add to menu
				// menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mMyListView.setMenuCreator(creator);

		// step 2. listener item click event
		mMyListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(final int position, SwipeMenu menu,
					int index) {
				// ApplicationInfo item = mAppList.get(position);
				switch (index) {
				case 0:
					onDelete(list.get(position).get(DBcolumns.CONTACTS_ID),
							position);
					ToastUtil.showToast(context, R.string.del_success);
					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							mMyListView.closeMenu();
						}
					}, 200);
					break;

				}
			}
		});

		// set SwipeListener
		mMyListView.setOnSwipeListener(new OnSwipeListener() {

			@Override
			public void onSwipeStart(int position) {
				// swipe start
			}

			@Override
			public void onSwipeEnd(int position) {
				// swipe end
			}
		});
	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_right:// 确认
			if (contactperson.getText().toString().equals("")||contactperson.getText().toString().replaceAll(" ", "").equals("")) {
				ToastUtil.showToast(context, R.string.name_no_empty);
				return;
			}
			if (telephone.getText().toString().equals("")) {
				ToastUtil.showToast(context, R.string.tel_no_empty);
				return;
			}
			if (!Phone.isPhoneNumberLenght(telephone.getText().toString())) {
				Toast.makeText(this,
						getString(R.string.phone_format_error),
						Toast.LENGTH_SHORT).show();
				return;
			}
			onWriteDB(contactperson.getText().toString(), telephone.getText()
					.toString(), "0");
			Bundle bundle = new Bundle();
			bundle.putString("name", contactperson.getText().toString());
			bundle.putString("telephone", telephone.getText().toString());
			Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(MainAttribute.REQUEST_CODE_PERSON, intent);
			onfinish();
			break;
		case R.id.layout_addresslist:
			//权限请求
			RxPermissions.getInstance(this)
					.request(Manifest.permission.READ_CONTACTS)
					.subscribe(new Action1<Boolean>() {
						@Override
						public void call(Boolean granted) {
							if (granted) { // Always true pre-M
								startActivityForResult(new Intent(Intent.ACTION_PICK,
										ContactsContract.Contacts.CONTENT_URI), requestCode);
							} else {
								ToastUtil.showToast(context, R.string.text_contacts_root);
							}
						}
					});
			break;
		// case R.id.clearall:
		// list.clear();
		// mCommonContactAdapter.notifyDataSetChanged();
		// Toast.makeText(ContactPersonActivity.this, "删除成功",
		// Toast.LENGTH_SHORT).show();
		// break;
		case R.id.btn_clear:
			onDelete(Value.CONTACTS_TYPE_HISTORY);
			if (mCommonContactAdapter.getCount() == 0) {
				mMyListView.removeFooterView(clearView);
				
			} else {
				mMyListView.addFooterView(clearView, null, false);
				layout_prompt.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.iv_contact_del:
			contactperson.setText("");
			break;
		case R.id.iv_tel_del:
			telephone.setText("");
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			try {
				ContentResolver reContentResolverol = getContentResolver();
				Uri contactData = data.getData();
				@SuppressWarnings("deprecation")
				Cursor cursor = managedQuery(contactData, null, null, null,
						null);
				cursor.moveToFirst();
				username = cursor
						.getString(cursor
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				String contactId = cursor.getString(cursor
						.getColumnIndex(ContactsContract.Contacts._ID));
				Cursor phone = reContentResolverol.query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
								+ " = " + contactId, null, null);
				while (phone.moveToNext()) {
					if (phone
							.getString(
									phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
							.substring(0, 2).equals("86")) {
						usernumber = phone
								.getString(
										phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
								.substring(
										2,
										phone.getString(
												phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
												.length()).trim();
					} else {
						usernumber = phone
								.getString(
										phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
								.replace("+86", "").trim();
					}
					telephone.setText(StringFilter.onStringToNumber(usernumber));
					contactperson.setText(username);
					contactperson.setSelection(contactperson.length());

				}
			} catch (Exception e) {
				ToastUtil.showToast(context, R.string.text_contacts_root);

			}
		}
	}

	class CommonContactAdapter extends BaseAdapter {
		private List<Map<String, String>> list;
		private Activity main;

		public CommonContactAdapter(Activity context,
				List<Map<String, String>> list) {
			this.list = list;
			main = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list != null ? list.size() : 0;
		}

		@Override
		public Map<String, String> getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder viewholder;
			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(main);
				convertView = (View) inflater.inflate(
						R.layout.listitem_commoncontact, null);
				viewholder = new ViewHolder();
				viewholder.name = (TextView) convertView
						.findViewById(R.id.name);
				viewholder.telephone = (TextView) convertView
						.findViewById(R.id.telephone);
				viewholder.cb_collection = (CheckBox) convertView
						.findViewById(R.id.cb_collection);
				convertView.setTag(viewholder);
			} else
				viewholder = (ViewHolder) convertView.getTag();
			viewholder.name.setText(list.get(position).get(
					DBcolumns.CONTACTS_NAME));
			viewholder.telephone.setText(list.get(position).get(
					DBcolumns.CONTACTS_TEL));
			viewholder.cb_collection.setChecked(list.get(position)
					.get(DBcolumns.CONTACTS_COLLECTION).equals("1") ? true
					: false);
			viewholder.cb_collection
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton v,
								boolean isCheck) {
							if (!v.isPressed())
								return;
							if (isCheck) {
								onUpdate(
										list.get(position).get(
												DBcolumns.CONTACTS_ID),
										list.get(position).get(
												DBcolumns.CONTACTS_NAME),
										list.get(position).get(
												DBcolumns.CONTACTS_TEL), "1");
							} else {
								onUpdate(
										list.get(position).get(
												DBcolumns.CONTACTS_ID),
										list.get(position).get(
												DBcolumns.CONTACTS_NAME),
										list.get(position).get(
												DBcolumns.CONTACTS_TEL), "0");
							}
						}
					});
			return convertView;
		}

		public class ViewHolder {
			TextView name, telephone;
			CheckBox cb_collection;
		}
	}
	@Override
	public void onFocusChange(View v, boolean focus) {
		if (v == contactperson) {

			if (focus) {
				if (contactperson.length() == 0) {
					iv_contact_del.setVisibility(View.GONE);
				} else {
					iv_contact_del.setVisibility(View.VISIBLE);
				}
			} else {
				iv_contact_del.setVisibility(View.GONE);
			}
		} else if (v == telephone) {
			iv_tel_del.setVisibility(View.VISIBLE);
			if (focus) {
				if (telephone.length() == 0) {
					iv_tel_del.setVisibility(View.GONE);
				} else {
					iv_tel_del.setVisibility(View.VISIBLE);
				}
			} else {
				iv_tel_del.setVisibility(View.GONE);
			}
		}

	}

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLoad(PullableListView pullableListView) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String contacts_id = mCommonContactAdapter.getItem(position).get(
				DBcolumns.CONTACTS_ID);
		String contacts_name = mCommonContactAdapter.getItem(position).get(
				DBcolumns.CONTACTS_NAME);
		String contacts_tel = mCommonContactAdapter.getItem(position).get(
				DBcolumns.CONTACTS_TEL);
		String contacts_collection = mCommonContactAdapter.getItem(position)
				.get(DBcolumns.CONTACTS_COLLECTION);
		onUpdate_sequence(contacts_id, contacts_name, contacts_tel,
				contacts_collection);
		Bundle bundle = new Bundle();
		bundle.putString("name", contacts_name);
		bundle.putString("telephone", contacts_tel);
		Intent intent = new Intent();
		intent.putExtras(bundle);
		setResult(MainAttribute.REQUEST_CODE_PERSON, intent);
		onfinish();
	}
}
